<template>
	<div class="admin-container">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<el-row :gutter="20">
				<el-col :span="4">
					<el-input v-model="searchParams.name" placeholder="请输入会员类型名称" clearable
						@keyup.enter.native="searchByName">
					</el-input>
				</el-col>
				<el-col :span="8">
					<el-button type="primary" @click="searchByName">查询</el-button>
					<el-button type="success" @click="showAddDialog">新增</el-button>
				</el-col>
			</el-row>
		</div>
		<!-- 信息展示区 -->
		<div class="table-container">
			<el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0">
				<el-table-column prop="name" label="会员类型名称">
				</el-table-column>
				<el-table-column prop="discount" label="折扣">
				</el-table-column>
				<el-table-column prop="description" label="描述">
				</el-table-column>
				<el-table-column prop="integral" label="积分要求">
				</el-table-column>
				
				<el-table-column prop="create_time" label="创建时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.create_time) }}
					</template>
				</el-table-column>
				<el-table-column prop="update_time" label="更新时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.update_time) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220">
					<template slot-scope="scope">
						<el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div v-else class="no-data">
				<p>没有找到匹配的数据</p>
			</div>
		</div>
		<!-- 分页组件 -->
		<div class="pagination-container">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page.sync="currentPage" :page-size.sync="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="allData.length">
			</el-pagination>
		</div>
		<!-- 编辑对话框 -->
		<el-dialog title="编辑会员类型" :visible.sync="editDialogVisible" width="30%">
			<el-form :model="currentRow" :rules="editRules" ref="editForm">
				<el-form-item label="会员类型名称" prop="name">
					<el-input v-model="currentRow.name"></el-input>
				</el-form-item>
				<el-form-item label="折扣" prop="discount">
					<el-input v-model="currentRow.discount"></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="currentRow.description"></el-input>
				</el-form-item>
				<el-form-item label="积分要求" prop="integral">
					<el-input v-model="currentRow.integral"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleUpdate">更新</el-button>
			</span>
		</el-dialog>
		<!-- 新增对话框 -->
		<el-dialog title="新增会员类型" :visible.sync="addDialogVisible" width="30%">
			<el-form :model="addUser" :rules="addRules" ref="addForm">
				<el-form-item label="会员类型名称" prop="name">
					<el-input v-model="addUser.name"></el-input>
				</el-form-item>
				<el-form-item label="折扣" prop="discount">
					<el-input v-model="addUser.discount"></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="addUser.description"></el-input>
				</el-form-item>
				<el-form-item label="积分要求" prop="integral">
					<el-input v-model="addUser.integral"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleAdd">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import axios from 'axios';
	import {
		Input,
		Row,
		Col,
		Button,
		Table,
		TableColumn,
		Dialog,
		Form,
		FormItem,
		Pagination,
		Message
	} from 'element-ui';

	export default {
		name: 'MembershipType',
		components: {
			'el-input': Input,
			'el-row': Row,
			'el-col': Col,
			'el-button': Button,
			'el-table': Table,
			'el-table-column': TableColumn,
			'el-dialog': Dialog,
			'el-form': Form,
			'el-form-item': FormItem,
			'el-pagination': Pagination
		},
		data() {
			return {
				allData: [], // 存储所有数据
				tableData: [], // 存储当前页的数据
				searchParams: {
					name: '',
				},
				editDialogVisible: false,
				currentRow: {
					name: '',
					discount: '',
					description: '',
					integral: '',
				},
				addDialogVisible: false,
				addUser: {
					name: '',
					discount: '',
					description: '',
					integral: '',
				},
				editRules: {
					name: [{
						required: true,
						message: '请输入会员类型名称',
						trigger: 'blur'
					}, ],
					discount: [{
						required: true,
						message: '请输入折扣',
						trigger: 'blur'
					}, ],
					integral: [{
						required: true,
						message: '请输入积分要求',
						trigger: 'blur'
					}, ],
				},
				addRules: {
					name: [{
						required: true,
						message: '请输入会员类型名称',
						trigger: 'blur'
					}, ],
					discount: [{
						required: true,
						message: '请输入折扣',
						trigger: 'blur'
					}, ],
					integral: [{
						required: true,
						message: '请输入积分要求',
						trigger: 'blur'
					}, ],
				},
				currentPage: 1,
				pageSize: 10,
			};
		},
		created() {
			this.fetchData();
		},
		methods: {
			getAuthorizationHeader() {
				const token = localStorage.getItem('Authorization');
				if (!token) {
					this.$message.error('未授权访问');
					return {};
				}
				return {
					'Content-Type': 'application/json',
					'Authorization': token
				};
			},
			fetchData() {
				const headers = this.getAuthorizationHeader();
				axios.get('http://localhost:8887/Membershiptype/findAll', {
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
						} else {
							Message.error('获取数据失败');
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						Message.error('请求失败，请检查网络或联系管理员');
					});
			},
			formatDate(value) {
				const date = new Date(value);
				return new Intl.DateTimeFormat('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				}).format(date);
			},
			searchByName() {
				const headers = this.getAuthorizationHeader();
				axios.get('http://localhost:8887/Membershiptype/selectMembershiptype', {
						headers,
						params: {
							name: this.searchParams.name
						}
					})
					.then(response => {
						if (response.data.code === 200 && response.data.data.length > 0) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
						} else {
							Message.error('未找到匹配的会员类型');
							this.tableData = []; // 清空表格数据
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						Message.error('请求失败，请检查网络或联系管理员');
					});
			},
			handleEdit(row) {
				this.currentRow = {
					...row
				};
				this.editDialogVisible = true;
				this.dialogTitle = '编辑会员类型';
			},
			handleDelete(id) {
				this.$confirm('确认删除这条记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const headers = this.getAuthorizationHeader();
					axios.post(`http://localhost:8887/Membershiptype/deleteMembershiptypeById?id=${id}`, null, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								Message.success('删除成功');
								this.fetchData();
							} else {
								Message.error('删除失败');
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							Message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					Message.info('已取消删除');
				});
			},
			handleUpdate() {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						const headers = this.getAuthorizationHeader();
						axios.post('http://localhost:8887/Membershiptype/updateMembershiptypeById', this
								.currentRow, {
									headers
								})
							.then(response => {
								if (response.data.code === 200) {
									Message.success('修改成功');
									this.editDialogVisible = false;
									this.fetchData();
								} else {
									Message.error('修改失败');
								}
							})
							.catch(error => {
								console.error('请求失败:', error);
								Message.error('请求失败，请检查网络或联系管理员');
							});
					} else {
						Message.error('表单验证失败');
					}
				});
			},
			handleAdd() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						const headers = this.getAuthorizationHeader();
						axios.post('http://localhost:8887/Membershiptype/addMembershiptype', this.addUser, {
								headers
							})
							.then(response => {
								if (response.data.code === 200) {
									Message.success('新增成功');
									this.addDialogVisible = false;
									this.fetchData();
								} else {
									Message.error('新增失败');
								}
							})
							.catch(error => {
								console.error('请求失败:', error);
								Message.error('请求失败，请检查网络或联系管理员');
							});
					} else {
						Message.error('表单验证失败');
					}
				});
			},
			showAddDialog() {
				this.addDialogVisible = true;
				this.addUser = {
					name: '',
					discount: '',
					description: '',
					integral: '',
				};
			},
			handleSizeChange(newSize) {
				this.pageSize = newSize;
				this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
					.pageSize);
			},
			handleCurrentChange(newPage) {
				this.currentPage = newPage;
				this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
					.pageSize);
			},
		}
	};
</script>

<style scoped>
	.admin-container {
		padding: 20px;
		max-width: 100%;
		overflow-x: auto;
	}

	.search-bar {
		margin-bottom: 20px;
	}

	.search-bar .el-row {
		justify-content: space-between;
	}

	.search-bar .el-button {
		margin-left: 10px;
	}

	.table-container {
		margin-top: 20px;
		overflow-x: auto;
	}

	.no-data {
		text-align: center;
		padding: 20px;
	}

	.pagination-container {
		margin-top: 20px;
		text-align: left;
	}

	.dialog-footer {
		text-align: right;
	}

	.el-dialog__body {
		padding: 20px;
	}

	.el-form-item {
		margin-bottom: 20px;
	}

	.el-form-item__label {
		font-weight: bold;
	}

	.el-button--primary {
		background-color: #13ce66;
		border-color: #13ce66;
	}

	.el-button--primary:hover {
		background-color: #11b55e;
		border-color: #11b55e;
	}
</style>